// pages/home/behalfPayment/behalfPayment.js
import orderIndex  from '../../../api/order';
import userIndex from '../../../api/user';
import Index from '../../../api/index';
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX:app.globalData.isIphoneX,
    isPhone:app.globalData.isPhone,
    modelPhone:false,
    orderNo:'',
    type:'share',
    orderInfo:null,
    isBtn:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   var that=this
    this.setData({
      orderNo:options.orderNo,
      type:options.type
    })
    var token=wx.getStorageSync('token')
    console.log(token)
    // if(token){
      var referrerId=options.referrerId?options.referrerId:''
      this.getLogin(referrerId)

    // }else{
    //   this.getOrderInfo()
    // }
    
  },
  //登录
  getLogin(referrerId){
    var that=this
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log(res)
          var params={
            code:res.code,
            referrerId:referrerId
          }
          Index.apiWxappLogin(params).then(ress=>{
            console.log(ress,'ressressress')
            if(ress.data.phone){
              app.globalData.isPhone=true
            }else{
              app.globalData.isPhone=false
            }      
            app.globalData.userInfo=ress.data
            app.globalData.token=ress.data.token
              wx.setStorageSync('userInfo',ress.data)
              wx.setStorageSync('token',ress.data.token)
              that.getOrderInfo()
          })
        }
      },
    });
  },
  getOrderInfo(){
    orderIndex.apiAgentOrderInfo({orderNo:this.data.orderNo}).then(res=>{
      var orderInfo=res.data
      orderInfo.endTime=''
      if(res.data.status==0){
        var serverLocalDate = new Date().getTime();
        //调用函数开始计时
        this.serverLocalDate(serverLocalDate);
        orderInfo.endTime=this.getendTime(orderInfo.createTime)
      }
      this.setData({
        orderInfo:orderInfo
      })
    })
  },
  getendTime(time){
    let now = new Date(time); // 获取当前时间
    // 将当前时间加上24小时
    let futureTime = new Date(now.getTime() + 24 * 60 * 60 * 1000); // 24小时的毫秒数 
    // 格式化时间为年-月-日 时:分:秒
    let year = futureTime.getFullYear();
    let month = String(futureTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并使用padStart确保是两位数
    let day = String(futureTime.getDate()).padStart(2, '0');
    let hours = String(futureTime.getHours()).padStart(2, '0');
    let minutes = String(futureTime.getMinutes()).padStart(2, '0');
    let seconds = String(futureTime.getSeconds()).padStart(2, '0'); 
    let formattedDate = `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    return formattedDate
  },
  //立即支付
  payNow(e){
    var that=this
    if(this.data.isBtn){
      return false
    }
    this.setData({
      isBtn:true
    })
    setTimeout(()=>{
      that.setData({
        isBtn:false
      })
    },2000)

    if(!this.data.isPhone){
      this.setData({
        modelPhone:true,
      })
    }else{
      this.payOrder(this.data.orderInfo.orderNo,this.data.orderInfo.relAmount)
    }
    
  },
  payOrder(orderNo,amount){
    var that=this
    wx.showLoading({
      title: '支付中'
    });
    orderIndex.apiAgentPay({orderNo:orderNo}).then(res=>{
      wx.requestPayment({
        timeStamp:res.data.timeStamp,
        nonceStr:res.data.nonceStr,
        package:res.data.package,
        signType:res.data.signType,
        paySign:res.data.paySign,
        success: (res) => {
          setTimeout(function () {
            wx.hideLoading();
          }, 1500)
          if(res.resultCode==6001){
            wx.showToast({
              title:'取消支付',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            }) 
          }else if(res.resultCode==6002){
          wx.showToast({
            title:'网络连接出错,请检查网络连接后重试',
              icon: 'none',
              duration:3000,
              success: function () {
                setTimeout(function () {
                  wx.hideLoading();
                }, 1500)
              }
            }) 
          }else{
           wx.redirectTo({
             url: `/pages/home/payResult/payResult?amount=${amount}&orderNo=${orderNo}`,
           })
          }
        },
        fail: (res) => {
          console.log(res)
          wx.showToast({
            title:"取消支付",
            icon: "none",
            duration:3000
          })
      
        }
      });
    })
    // wx.navigateTo({
    //   url: `/pages/home/choosePay/choosePay?amount=${amount}&&orderNo=${orderNo}`,
    // })
  },
   //服务器系统时间开始计时
   serverLocalDate: function (serverLocalDate) {
    var _this = this;
    let newDate = serverLocalDate;
    _this.setData({
      servicetimeInterval: setInterval(function () { // 循环执行  
        newDate = (newDate / 1000 + 1) * 1000;
        _this.setData({
          systimestamp: newDate
        })
      }, 1000)  // 每秒执行一次以达到更新时间的目的
    })
  },
  closeLoginBtn(){
    this.setData({
      modelPhone:false,
    })
  },
  getPhoneNumber(e){
    var that=this
    var code=e.detail.code
    if(code){
      userIndex.apigetPhone({code:code}).then(res=>{
        app.globalData.isPhone=res.data.phone?true:false
        this.setData({
          isPhone:res.data.phone?true:false,
          modelPhone:false
        })
        this.getFullGiftProgress()
        this.getMarketingactivitySekKillRroducts()
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that=this
    setTimeout(()=>{
      that.setData({
        isPhone:app.globalData.isPhone,
      })
    },200)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    console.log(e)
    var userId=wx.getStorageSync('userInfo')?wx.getStorageSync('userInfo').userId:''
    var orderNo=this.data.orderNo
    return {
      title: '订单代付', // 分享标题
      path: `/pages/home/behalfPayment/behalfPayment?referrerId=${userId}&orderNo=${orderNo}&type=pay`, // 分享路径，必须是已经存在的页面路径
      // imageUrl: 'https://example.com/share.jpg', // 分享图标
      success: function (res) {
        // 转发成功
        if (res.errMsg === 'shareAppMessage:ok') {
          console.log('分享成功');
        }
      },
      fail: function (res) {
        // 转发失败
        console.log('分享失败', res);
      }
    }

  }
})